import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { AnalysisService } from '../analysis.service';
import { Router } from '@angular/router';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApesMessageService } from '@shared/apes/message';

@Component({
  selector: 'company-modal',
  templateUrl: './company-modal.component.html',
  styleUrls: ['./company-modal.component.scss'],
})
export class CompanyModalComponent implements OnInit {
  @Output() paramsOut = new EventEmitter();
  @Input() control: any;
  userInfo = this.userAuthService.getUserInfoObj();
  isVisible: boolean = false;
  userCompany: any;
  userData = [];
  button = [
    { name: '全国', id: 'all' },
    { name: '确认', id: 'isOk' },
  ];
  buts = [
    { name: '直营', id: 'direct', checked: false },
    { name: '合伙人', id: 'partner', checked: false },
    { name: '赋能', id: 'join', checked: false },
  ];
  companyLocal = this.as.getLocalObj();
  href = window.location.hash.slice(1);
  windowSize: number;

  constructor(private as: AnalysisService,
              private userAuthService: UserAuthService,
              private msg: ApesMessageService) {
  }

  ngOnInit() {
    const _body = document.querySelector('body');
    this.windowSize = _body.clientWidth;
    this.as.getLocalPermitA(this.userAuthService.getUserInfoObj().userAccount.post.localPermit.id).subscribe(
      () => this.getNewLocal()
    );
  }

  private $(id) {
    return document.getElementById(id);
  }

  /** 勾选公司 **/
  changeCompany($event, item: any, index, check, click?: any) {
    $event.preventDefault();           // 阻止默认事件
    let key = $event.keyCode;
    if (click === 1) {
      key = 13;
    }
    let nextId;
    let data = item['array'];

    switch (key) {
      case 13:
        this.allCompany(item, index, check);
        break;
      case 38:
        if (index <= 0) {
          index = data.length - 1;
          nextId = data[index].id;
        } else {
          nextId = data[index - 1].id;
        }
        this.$(nextId).focus();
        break;
      case 40:
        if (index >= data.length - 1) {
          nextId = data[0].id;
        } else {
          nextId = data[index + 1].id;
        }
        this.$(nextId).focus();
        break;
      case 37:
        this.$('direct').focus();
        break;
      case 39:
        this.$('isOk').focus();
        break;
    }

  }

  /** 选公司通用 **/
  allCompany(item: any, index, check, key?:any) {
    // debugger;
    const list = item['array'];
    const companyId = list[index].id;
    list[index].checked = !check;
    // !check ? this.userData.push(companyId) : this.userData[this.userData.indexOf(companyId)] = '';
    if(!check) {
      this.userData[this.userData.indexOf(companyId)] = '';
      this.userData.push(companyId)
    }else {
      this.userData[this.userData.indexOf(companyId)] = '';
    }
    this.userData = this.as.unique(this.userData);
    this.userData = this.as.remove(this.userData);
    let arr = [];
    for (let it of list) {
      arr.push(it.checked);
      arr = this.as.unique(arr);
    }
    if (arr.length > 1) {
      item.status = 'semiselection';   // 部分选
    } else {
      if (arr[0] == false) {
        item.status = 'notselected';   // 都不选
        // this.buts[index].checked = true;
      } else {
        item.status = 'selectall';   // 全选
        // this.buts[index].checked = false;
      }
    }
  }

  /** 切换运营模式 **/
  changeOperation($event, index, click?: any) {
    $event.preventDefault();           // 阻止默认事件
    let key = $event.keyCode;
    if (click === 1) {
      key = 13;
    }
    let nextId;

    switch (key) {
      case 13:
        this.switchOperation(index);
        break;
      case 38:
        if (index <= 0) {
          index = this.buts.length - 1;
          nextId = this.buts[index].id;
        } else {
          nextId = this.buts[index - 1].id;
        }
        this.$(nextId).focus();
        break;
      case 40:
        if (index >= this.buts.length - 1) {
          nextId = this.buts[0].id;
        } else {
          nextId = this.buts[index + 1].id;
        }
        this.$(nextId).focus();
        break;
      case 37:
        this.$('isOk').focus();
        break;
      case 39:
        for (let item of this.userCompany) {
          if (item.disable === 'block') {
            nextId = item['array'][0].id;
            this.$(nextId).focus();
          }
        }
        break;
    }
  }

  /** 切换运营模式-方法 **/
  switchOperation(index: any) {
    const list = this.userCompany[index];
    for (let i = 0, len = this.userCompany.length; i < len; i++) {
      if (i !== index) {
        this.userCompany[i]['disable'] = 'none';
      }
    }
    if (list['disable'] === 'none') {
      list['disable'] = 'block';
    }
    this.buts[index].checked = !this.buts[index].checked;
    for (let i = 0 , len = list['array'].length; i< len; i++) {
      if (this.buts[index].checked) {
        list['array'][i]['checked'] = true;
        this.allCompany(list, i, false, index);
      } else {
        list['array'][i]['checked'] = false;
        this.allCompany(list, i, true, index);
      }
    }
  }

  /** 自动获取焦点 ***/
  getMenus(id) {
  }

  /** 确认、全国按钮 **/
  changeMenu($event, postId: string, index, click?: any) {
    $event.preventDefault();           // 阻止默认事件
    let key = $event.keyCode;
    if (click === 1) {
      key = 13;
    }
    let id = $event.target.id;
    let nextId;

    switch (key) {
      case 13:
        if (id === 'all') {   // 全选
          this.allChanges();
        } else if (id === 'isOk') {    // 确认
          this.changeChild();
        }
        break;
      case 38:
        if (index <= 0) {
          index = this.button.length - 1;
          nextId = this.button[index].id;
        } else {
          nextId = this.button[index - 1].id;
        }
        this.$(nextId).focus();
        break;
      case 40:
        if (index >= this.button.length - 1) {
          nextId = this.button[0].id;
        } else {
          nextId = this.button[index + 1].id;
        }
        this.$(nextId).focus();
        break;
      case 37:
      case 39:
        nextId = this.buts[0].id;
        this.$(nextId).focus();
        break;
    }
  }

  /** 确认 **/
  changeChild() {
    this.as.storeLocal(JSON.stringify(this.userCompany));
    if (this.control === 'car') {
      this.$(0).focus();
    } else {
      this.$('system').focus();
    }
    if(JSON.stringify(this.userData) !== '[]') {
      this.userData = this.as.unique(this.userData);
      this.userData = this.as.remove(this.userData);
      this.paramsOut.emit(this.userData);
      this.isVisible = false;
    }else {
      this.msg.error('公司不能为空，请勾选公司');
    }
  }

  /** 全国 **/
  allChanges() {
    this.as.getLocalPermit(this.userInfo.userAccount.post.localPermit.id);
    this.getNewLocal();
    this.paramsOut.emit(this.userData);
    this.isVisible = false;
  }

  /** 调用获取公司 **/
  getNewLocal() {
    this.userCompany = this.companyLocal;
    const data = [];
    for (let item of this.userCompany) {
      for (let list of item['array']) {
        list.checked = true;
        item.status = 'selectall';
        item.disable = 'none';
        data.push(list.id);
      }
    }
    this.userData = this.as.unique(data);
  }


}
